package gr.handmademarket.ui.pages;

import gr.handmademarket.bl.operations.LoginOperation;
import gr.handmademarket.po.implementations.Buyer;
import gr.handmademarket.po.interfaces.User;
import gr.handmademarket.ui.WebHandMadeSession;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;


/**
 * page for creating an account.
 */
public class LoginPage 
extends CommonTemplatePage{

	/**
	 * the form containing the user credentials.
	 */
	@SuppressWarnings("nls")
	private Form<User> form = new Form<User>("uform", new CompoundPropertyModel<User>(new Buyer()));
	
	/**
	 * the username field.
	 */
	@SuppressWarnings("nls")
	private TextField<String> usernameField = new RequiredTextField<String>("username");
	
	/**
	 * the password field.
	 */
	@SuppressWarnings("nls")
	private TextField<String> passwordField = new RequiredTextField<String>("password");
	
	/**
	 * submit link.
	 */
	@SuppressWarnings("nls")
	private AjaxButton submit = new AjaxButton("submitBtn", form) {

		/**
		 * serialVersionUID.
		 */
		private static final long serialVersionUID = 1L;

		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			LoginOperation op = new LoginOperation();
			op.setUsername(form.getModelObject().getUsername());
			op.setPassword(form.getModelObject().getPassword());
			op.execute();
			User user = op.getUser();
			if (user != null){
				WebHandMadeSession session = (WebHandMadeSession) WebHandMadeSession.get();
				session.setUser(user);
				setResponsePage(HomePage.class);
			} else{
				error("user not authenticated");
				target.focusComponent(LoginPage.this.get("feedbackPanel"));
			}
		}
		
		@Override
		protected void onError(AjaxRequestTarget target, Form<?> form1) {
			target.focusComponent(LoginPage.this.get("feedbackPanel"));
		}
		
	};

	
	/**
	 * Creates a new LoginPage object. 
	 */
	public LoginPage(){
		super();
		add(form);
		form.add(usernameField, passwordField, submit);
	}
	
}
